import 'dart:convert';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:zy_pos_demo/datarepository/bean/demo.dart';
import 'package:zy_pos_demo/datarepository/bean/login/loginbeans.dart';
import 'package:zy_pos_demo/datarepository/bean/requestparams.dart';
import 'package:zy_pos_demo/datarepository/bean/takeoutbean.dart';
import 'package:zy_pos_demo/datarepository/constants/constant.dart';
import 'package:zy_pos_demo/datarepository/local/spdata.dart';
import 'package:zy_pos_demo/datarepository/remote/urls.dart';
import 'package:zy_pos_demo/datarepository/util/utils.dart';

//flutter似乎不使用系统的代理（大多数其他应用程序都使用代理），所以我无法使用charles进行调试。则需要手动添加代码加入代理

class DioHttpHelper {
  static final DioHttpHelper _helper = DioHttpHelper._internal();

  DioHttpHelper._internal();

  factory DioHttpHelper() => _helper;

  static const BASE_URL = "http://api.beta.acewill.net/";
  static const USE_PROXY = true;
  static const PROXY_IP = 'PROXY 10.0.10.60:8888';
  static const PROXY_NOT = 'DIRECT';
  static const CONNECT_TIMEOUT = 5000;
  static const RECEIVE_TIMEOUT = 3000;
  static Dio dio;

  static Dio getInstance() {
    if (dio == null) {
      var options = BaseOptions(
        baseUrl: BASE_URL,
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT,
        contentType: Headers.formUrlEncodedContentType,
      );
      dio = Dio(options);
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.findProxy = (Uri) {
          // 用1个开关设置是否开启代理
          return USE_PROXY ? PROXY_IP : PROXY_NOT;
        };
      };
//      dio.interceptors.add(LoggerInterceptors());
      dio.interceptors.add(LogInterceptor());
      /*dio.interceptors
          .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
        // 在请求被发送之前做一些事情
        return options; //continue
        // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
        // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
        //
        // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
        // 这样请求将被中止并触发异常，上层catchError会被调用。
      }, onResponse: (Response response) async {
        // 在返回响应数据之前做一些预处理
        return response; // continue
      }, onError: (DioError e) async {
        // 当请求失败时做一些预处理
        return e; //continue
      }));*/
    }
    return dio;
  }

  Future<LoginBean> login(
      {String account, String pwd}) async {
    String getExpired() {
      return StringUtil.dateFormat(
          dateTime: DateTime.now().add(Duration(days: 1)));
    }

    void initJPush(String tag) {
      /*JPush jpush = new JPush();
      // 配置jpush(不要省略）
      jpush.setup(
          appKey: "841582c67ef491418f5978ef", channel: 'developer-default');
      // 监听jpush
      jpush.setTags([tag]);
      jpush.addEventHandler(
        onReceiveNotification: (Map<String, dynamic> message) async {
          print("flutter 接收到推送: $message");
        },
        onOpenNotification: (Map<String, dynamic> message) {
          // 点击通知栏消息，在此时通常可以做一些页面跳转等
        },
      );*/
    }

    Dio _dio = getInstance();
    LoginParams req = LoginParams(
      mid: account,
      pwd: pwd,
      expired: getExpired(),
      sn: ConstantString.SN,
    );
    Map<String, String> params =
        StringUtil.createRequestBody(req: req.toJson());
    Response response = await _dio.post(Urls.login, data: params);
    LoginBean bean = LoginBean.fromJson(response.data);
    if (bean.errcode == 0) {
      SPHelper().saveUserAccount(account: account);
      initJPush(bean.res.loginInfo.sid);
    }
    return bean;
  }

  Future<TakeOutBean> getNumber(TakeOutParams req) async {
    Dio _dio = getInstance();
    Map<String, String> params =
        StringUtil.createRequestBody(req: req.toJson());
    Response response = await _dio.post(Urls.takeOut, data: params);

    return TakeOutBean.fromJson(response.data);
  }

  Future<List<DemoBean>> getDemo(
      {String account, String pwd}) async {
    Dio _dio = getInstance();
    Response response =
        await _dio.get("https://api.github.com/orgs/flutterchina/repos");
    List data = response.data;
    List<DemoBean> result = [];
    for (Map<String, dynamic> value in data) {
      print("id=${value['id']};name=${value["full_name"]}");
      result.add(DemoBean.fromJson(value));
    }
    return result;
  }
}

class OkHttpUtil {
  OkHttpUtil._internal();

  static final OkHttpUtil _httpUtil = OkHttpUtil._internal();

  factory OkHttpUtil() => _httpUtil;

  Future<Map> login({String account, String pwd}) async {
    String getExpired() {
      return StringUtil.dateFormat(
          dateTime: DateTime.now().add(Duration(days: 1)));
    }

    Map<String, String> req = {};
    req["mid"] = account;
    req["pwd"] = pwd;
    req["expired"] = getExpired();
    req["sn"] = ConstantString.SN;
    Map<String, String> params = {};
    params["req"] = jsonEncode(req);
    params["appid"] = "1186529944";
    params["ts"] = StringUtil.getTS();
    params["sig"] = "111";

    var client = http.Client();

    http.Response response = await client
        .post("http://api.beta.acewill.net/" + Urls.login, body: params);
    print(response.body);

    return null;
  }
}
